package controllers

import (
	"fly/helper"
	"fly/models"
	"fly/req"
	"fly/resp"
	"fly/schema"
	"fly/service"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"github.com/duke-git/lancet/v2/condition"
	"github.com/duke-git/lancet/v2/maputil"
	"net/url"
)

// LifetimeController 有寿维护
type LifetimeController struct {
	BaseController
	AircraftComponentService service.AircraftComponentService
	LifetimeRecordService    service.LifetimeRecordService
	AircraftService          service.AircraftService
	SysUserService           service.SysUserService
	SysDictService           service.SysDictService
}

// Save ...
// @Title 添加或者编辑有寿维护
// @Description 添加或者编辑有寿维护
// @Param token header  string	false "授权Token"
// @Param body body []req.LifetimeRecordReq true "添加或者编辑有寿维护"
// @Success 200 {object} []resp.LifetimeRecordResp
// @router /save [post]
func (c *LifetimeController) Save() {
	var params []*req.LifetimeRecordReq
	c.CheckReqErrorAbort(c.BindJSON(&params))
	for _, param := range params {
		c.ValidReqParams(param)
	}
	var respList []resp.LifetimeRecordResp
	for _, con := range params {
		c.CheckReqErrorAbort(helper.RequireTrue(maputil.HasKey(schema.MaintenanceMap, con.Type), "不支持的维护类型"))
		c.CheckReqErrorAbort(helper.RequireTrue(maputil.HasKey(schema.ComponentMap, con.ComponentType), "不支持的组件类型"))
		c.CheckReqErrorAbort(helper.RequireTrue(maputil.HasKey(schema.AdjustMap, con.AdjustType), "不支持的操作类型"))
		mRecord := models.LifetimeRecord{}
		c.CheckReqErrorAbort(helper.CopyDeep(&mRecord, con))
		var err error
		// 检查飞机
		aircraft, err := c.AircraftService.GetSimpleAircraftById(con.AircraftId)
		uid := c.GetReqUserId()
		c.CheckReqErrorAbort(err)
		r := resp.LifetimeRecordResp{}
		if con.IntervalDuration == 0 && con.IntervalCount == 0 {
			if con.Type == schema.LifetimeTypeBody {
				// 机体A检
				con.IntervalDuration = schema.BodyIntervalDuration
				con.IntervalCount = schema.BodyIntervalCount
			} else if con.AdjustType == schema.AdjustTypeCorrection {
				// 其他在校正的情况下才由前端传入
				c.CheckReqErrorAbort(fmt.Errorf("须传入下次保养间隔(次数)"))
			}
		}
		if con.Type == schema.LifetimeTypeBody {
			// 机体A检,需要更新飞机降落次数
			c.CheckReqErrorAbort(helper.RequireTrue(con.WorkCount > 0, "须传入起落次数"))
			mAircraft := models.Aircraft{BaseModel: models.BaseModel{Id: con.AircraftId, Updater: uid}}
			mAircraft.TotalUpDown = con.WorkCount
			_, err = orm.NewOrm().Update(&mAircraft, "updater", "total_up_down")
			c.CheckRespErrorAbort(err)
		}
		// 检查保存组件
		component, err := c.AircraftComponentService.CheckAddComponentByType(con.AircraftId, con.ComponentType, uid)
		c.CheckRespErrorAbort(err)
		// 更新记录到组件下
		err = c.AircraftComponentService.SaveComponentCountDuration(component.Id, con.LifetimeCountDurationReq, uid)
		c.CheckRespErrorAbort(err)
		mRecord.ComponentId = component.Id
		id, err := models.AddLifetimeRecord(&mRecord, uid)
		record, err := models.GetLifetimeRecordById(id)
		err = resp.Copy2TimeResp(&r, record)
		c.CheckRespErrorAbort(err)
		r.ComponentId = component.Id
		r.ComponentType = component.Type
		r.ComponentName = component.Name
		r.IntervalDuration = component.IntervalDuration
		r.IntervalCount = component.IntervalCount
		r.AircraftCode = aircraft.Code
		r.AdjustTypeName = schema.AdjustMap[mRecord.AdjustType]
		r.CreatorName, err = c.SysUserService.GetUserRealNameById(uid)
		r.UpdaterName = r.CreatorName
		c.CheckRespErrorAbort(err)
		respList = append(respList, r)
	}
	c.Success(respList)
}

// Index ...
// @Title 有寿维护列表
// @Description 有寿维护列表
// @Param token header  string	false "授权Token"
// @Param keywords query  string false "搜索字段"
// @Param pageNum query  int false "当前页"
// @Param pageSize query  int false "每页数量"
// @Param total query  int false "数据总数"
// @Param code query  string false "飞机编号"
// @Param type query  int false "维护任务类型"
// @Success 200 {object} []service.Pagination
// @router / [get]
func (c *LifetimeController) Index() {
	params, _ := url.ParseQuery(c.Ctx.Request.URL.RawQuery)
	data, pagination := c.LifetimeRecordService.GetPaginateData(params)
	var recordList []resp.LifetimeRecordResp
	c.CheckRespErrorAbort(resp.Copy2TimeResp(&recordList, &data))
	for i, record := range data {
		recordList[i].CreatorName, _ = c.SysUserService.GetUserRealNameById(record.Creator)
		recordList[i].UpdaterName, _ = c.SysUserService.GetUserRealNameById(record.Updater)
		component, _ := c.AircraftComponentService.GetComponentById(record.ComponentId)
		if component != nil {
			recordList[i].ComponentType = component.Type
			recordList[i].ComponentName = component.Name
			recordList[i].ComponentName = component.Name
			recordList[i].IntervalDuration = component.IntervalDuration
			if component.LatestFlightTime != nil {
				recordList[i].LatestFlightTime = helper.UnixMilli(*component.LatestFlightTime)
			}
			recordList[i].IntervalCount = component.IntervalCount
		}
		aircraft, _ := c.AircraftService.GetSimpleAircraftById(record.AircraftId)
		if aircraft != nil {
			recordList[i].AircraftCode = aircraft.Code
			recordList[i].RecordCount = c.LifetimeRecordService.GetRecordCount(aircraft.Id,
				condition.TernaryOperator(component != nil, component.Id, 0))
		}
		recordList[i].AdjustTypeName = schema.AdjustMap[record.AdjustType]
	}
	pagination.List = recordList
	c.Success(pagination)
}
